const rewiredServer = require('@ifchange-engr/rewired-server');

const rewiredMicro = require('@ifchange-engr/rewired-micro');
const rewiredAliases = require('@ifchange-engr/rewired-aliases');
const VirtualModuleWebpackPlugin = require('virtual-module-webpack-plugin');
const { getBabelLoader, paths } = require('@ifchange-engr/scripts-util');
const fs = require('fs');
const path = require('path');


class ExampleResolverPlugin {
    apply(resolver) {
        resolver.getHook('before-file').tapPromise('ExampleResolverPlugin', async (request) => {
            const flag = '@example', index = request.path.indexOf(flag);
            if (index > -1) {
                request.path = path.resolve(paths.appRoot, 'packages', request.path.substring(index + flag.length + 1), 'example/index');
            }
        });
    }
}

const getCoreList = () => {
    const list = fs.readdirSync(path.resolve(paths.appRoot, 'packages'))
        .filter((name) => {
            const examplePath = path.resolve(paths.appRoot, 'packages', name, 'example', 'index.js');
            return fs.existsSync(examplePath);
        });

    return `import loadable from '@loadable/component';
export default {
  ${list.map((name) => `'${name}': loadable(()=>import('@example/${name}'))`).join(',')}
}`;

    return list;
};

module.exports = (config, env) => {
    
    config = rewiredAliases({
        handlebars: 'handlebars/dist/handlebars.min.js',
        '@root': paths.appRoot,
        '@packages': path.resolve(paths.appRoot, 'packages'),
        '@src': path.resolve(paths.appSrc)
    })(config);

    config.resolve.plugins.push(new ExampleResolverPlugin());
    const babelLoader = getBabelLoader(config.module.rules);
    if (!Array.isArray(babelLoader.include)) {
        babelLoader.include = [babelLoader.include];
    }
    babelLoader.include.push(path.resolve(process.cwd(), 'packages'));


    const htmlWebpackPlugin = config.plugins.find((plugin) => plugin.constructor.name === 'HtmlWebpackPlugin');
    htmlWebpackPlugin.options.title = 'ifchange-core';

    // 添加虚拟模块
    config.plugins.push(new VirtualModuleWebpackPlugin({
        moduleName: './src/euiMap.js',
        contents: getCoreList()
    }));

    const oneOfRule = config.module.rules.find(
        rule => rule.oneOf !== undefined
    );
    
    const rawRules = {
        test: /.(md|code)$/,
        loader: require.resolve('raw-loader')
    }

    if (oneOfRule) {
        oneOfRule.oneOf.unshift(rawRules);
    } else {
        config.module.rules.push(rawRules);
    }

    config = rewiredMicro(config, env);

    config = rewiredServer(config, env);

    return config;
};

